import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { db } from '@/storage'
import { tokenConfig, configSetting } from '@/config'
import router from '@/router'
import { userStore } from '@/store'
import { ElMessage } from 'element-plus'

export const handlerRequstConfig = (config: InternalAxiosRequestConfig) => {
  const { key, value } = tokenConfig.token
  const token = db.get('token')
  const tokenKeys: Record<string, string> = {}
  if (key) {
    tokenKeys[key] = value.split(' ')[0] + ' ' + token
  }
  let _header: any = {}
  if (token) {
    _header = {
      ..._header,
      ...tokenKeys
    }
  }

  // 查询是否超时
  const time = db.get('expires')
  if (new Date().getTime() - time > tokenConfig.token?.expires) {
    router.push({
      name: configSetting.LoginMainLayoutName
    })
  }
  return { ...config, headers: { ...config.headers, ..._header } }
}

export const failAuth = () => {
  userStore()
    .logout()
    .then(() => {
      router.replace({
        name: configSetting.LoginMainLayoutName
      })
    })
}

export const failCodeMap = new Map([
  [400, { msg: '请求错误' }],
  [401, { msg: '未认证', handler: failAuth }],
  [403, { msg: '未授权' }],
  [404, { msg: '请求地址错误' }],
  [405, { msg: '请求方式错误' }],
  [408, { msg: '请求超时' }],
  [422, { msg: '验证错误' }],
  [500, { msg: '服务器内部错误' }],
  [501, { msg: '服务未实现' }],
  [502, { msg: '网关错误' }],
  [503, { msg: '服务不可用' }],
  [504, { msg: '网关超时' }],
  [505, { msg: 'HTTP版本不受支持' }]
])

export const handlerErrorCode = (error: any) => {
  if (!error.response) return Promise.reject(new Error('网络异常或异常错误'))
  const { status } = error.response

  const { msg, handler }: any = failCodeMap.get(status)
  ElMessage({
    type: 'error',
    message: msg
  })
  if (handler && typeof handler === 'function') handler()
  return Promise.reject(error.response)
}

export const handlerSucessResponse = (response: AxiosResponse) => {
  if (response.status) {
    const { code, msg } = response.data
    // 登录成功
    if (code === 200) {
      return response.data
    }
    ElMessage.error(msg || '系统出错')
    return Promise.reject(new Error(msg || 'Error'))
  }
}
